package com.turing.auth_server.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.turing.auth_server.domain.AuthUser;
import com.turing.auth_server.feign.AdminService;
import enums.ErrorCode;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import result.Result;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Result result = adminService.getAdminByLoginAccount(username);
        if (result.getCode()!= ErrorCode.SUCCESS.getCode() || result.getData()==null){
            throw new InternalAuthenticationServiceException("用户"+username+"不存在");
        }
        JSONObject account = JSONObject.parseObject(JSON.toJSONString(result.getData()));
        //权限集合
        Set<SimpleGrantedAuthority> grantedAuthoritySet = new HashSet<>();
        AuthUser user = new AuthUser(account.getString("loginAccount"),account.getString("loginPassword"),grantedAuthoritySet);
        return user;
    }
}
